// pages/bard/bard.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageSrc: '',
    aspectRatio: '',
    // description: '',
    poem: '',
    biaoti: '《登黄鹤楼》',
    sentences: ['昔人已乘黄鹤去'+'，', '此地空余黄鹤楼'+'。', '黄鹤一去不复返'+'，', '白云千载空悠悠'+'。']
  },

  chooseImage: function() {
    let that = this;
    wx.chooseMedia({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFiles = res.tempFiles;
        const fileSizeLimit = 1;
        if (tempFiles.length > 0) {
          const tempFilePath = tempFiles[0].tempFilePath;
          // wx.compressImage({
          //   src: tempFilePath,
          //   quality: 80,
          //   success(res) {
          //     const compressedTempFilePath = res.tempFilePath;
          //     that.uploadImage(compressedTempFilePath);
          //   }
          // });
          wx.getImageInfo({
            src: tempFilePath,
            success(res) {
              const width = res.width;
              const height = res.height;
              const aspectRatio = `${width / height * 30}vh`;
              that.setData({
                aspectRatio: aspectRatio
              });
            },
            fail(err) {
              console.error('获取图片信息失败：', err);
            }
          });

          wx.getFileSystemManager().getFileInfo({
            filePath: tempFilePath,
            success(res) {
              let quality = 100;
              let compressedSize = res.size / (1024 * 1024).toFixed(2);
              console.log(compressedSize);
              if (compressedSize > fileSizeLimit) {
                quality = quality * fileSizeLimit / (compressedSize + 0.1);

                wx.compressImage({
                  src: tempFilePath,
                  quality: quality,
                  success(res) {
                    const newTempFilePath = res.tempFilePath;
                    wx.getFileSystemManager().getFileInfo({
                      filePath: newTempFilePath,
                      success(res) {
                        compressedSize = res.size / (1024 * 1024).toFixed(2);
                        console.log(compressedSize);
                        if (compressedSize <= fileSizeLimit) {
                          that.uploadImage(newTempFilePath);
                        }
                      }
                    })
                  }
                })
              } else {
                that.uploadImage(tempFilePath);
              }
            },
            fail(err) {
              console.error('获取图片信息失败：', err);
            }
          })
        }
        that.setData({
          imageSrc: tempFiles[0].tempFilePath,
        });
      },
      fail(err) {
        console.error('获取图片信息失败：', err);
      }
    });
  },

  callBaiduAI: function(imageUrl) {
    let that = this;
    this.getAccessToken().then(token => {
      wx.request({
        url: `https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/request?access_token=${token}`,
        method: 'POST',
        header: {'Content-Type': 'application/json'},
        data: {
          question: '请描述图片内容',
          url: imageUrl,
        },
        success: function(res) {
          console.log("data", res.data);
          setTimeout(() => {
            that.getResult(res.data.result.task_id);
          }, 25000);
          ;
        },
        fail: function(err) {
          console.log(err);
        }
      });
    }).catch(error => {
      console.error('请求AccessToken失败', error);
    });
  },

  getResult: function(taskId) {
    let that = this;
    this.getAccessToken().then(token => {
      wx.request({
        url: `https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/get-result?access_token=${token}`,
        method: 'POST',
        header: {'Content-Type': 'application/json'},
        data: {
          task_id: taskId
        },
        success: function(res) {
          console.log(res.data.result.ret_msg);
          // that.data.description = res.data.result.description;
          that.callKimiApi(res.data.result.description);
        },
        fail: function(err) {
          console.log(err);
        }
      });
    })
  },

  getAccessToken: function(){
    const API_KEY = '4dlB99pcsw9ynfSzH1K0Cviv';
    const SecretKey = 'sLP9FUByxbsOK0Waiajb0PIWQUBXZwtD';

    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SecretKey}`,
        // method: 'POST',
        // data: {
        //   grant_type: 'client_credentials',
        //   client_id: API_KEY,
        //   client_secret: SecretKey,
        // },
        success: function(res) {
          if (res.statusCode === 200 && res.data.access_token) {
            resolve(res.data.access_token)
          } else {
            reject('获取AccessToken失败：' + (res.data.error || '未知错误'));
          }
        },
        fail: function(err) {
          reject('请求失败：', + err.errMsg);
        }
      })
    })
  },

  uploadImage: function(filePath) {
    let that = this;
    const token = '4754bceeb7e1ef81453da3841529b40a';
    const repoOwner = 'gu-taiyang';
    const repoName = 'wechat_img';
    const fileName = 'upload/' + new Date().getTime() + '.jpg';
    const imageUrl = `https://gitee.com/${repoOwner}/${repoName}/raw/master/${fileName}`;

    wx.uploadFile({
      filePath: filePath,
      name: 'file',
      url: `https://gitee.com/api/v5/repos/${repoOwner}/${repoName}/contents/${fileName}`,
      header: {
        'Authorization': `token ${token}`
      },
      formData: {
        content: wx.getFileSystemManager().readFileSync(filePath, 'base64'),
        message: 'upload image'
      },
      success(res) {
        // console.log('上传成功', res.data);
        console.log(imageUrl);
        that.callBaiduAI(imageUrl);
      },
      fail(err) {
        console.log('上传失败', err);
      }
    });
  },

  parsePoem: function() {
    wx.showToast({
      title: '生成中',
      icon: 'loading',
      duration: 30000,
    });
    setTimeout(() => {
      let poem = this.data.poem;
      console.log(poem);
      if (poem != '') {
        let lines = poem.split('\n');
        let biaoti = lines[0].replace('标题：', '');
        let sentences = lines.slice(1).map(sentence => sentence.trim());
        this.setData({
          biaoti: biaoti,
          sentences: sentences
        });
      } else {
        wx.showToast({
          title: '请重试',
          icon: 'none'
        })
      }
    }, 30000);
  },

  callKimiApi: function(description) {
    const API_KEY = 'sk-6qCX5qyJMyjIjR9rI3yCRvlDscFgHVusO5Svsop2zuy52TnX';
    const BASE_URL = 'https://api.moonshot.cn/v1/chat/completions';

    let that = this;
    wx.request({
      url: BASE_URL,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      data: {
        model: 'moonshot-v1-8k',
        messages: [
          {
            "role": "user",
            "content": `${description}，请根据描述作一首七言绝句，一共四句，每句七个字。要求：格式为第一行：“标题：《》”，后面每一行七个字，中间不要有空行`
          }
        ],
        // files: [{url: imageUrl}]
      },
      success: function(apiRes) {
        let poem = apiRes.data.choices[0].message.content;
        that.setData({
          poem: poem
        });
      },
      fail: function(err) {
        wx.showToast({
          title: '请重试',
          icon: 'none'
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})